from django.contrib.sites.models import Site
from django.contrib.syndication.feeds import Feed, ObjectDoesNotExist, FeedDoesNotExist
from django.core.urlresolvers import reverse

from popboard.models import Post, Category, Thread

class LatestPosts(Feed):
    title = '%s Latest Discussions' % (Site.objects.get_current().name)
    description = "The latest contributions to discussions."
    title_template = "popboard/feeds/latest_title.html"
    description_template = "popboard/feeds/latest_description.html"
    link = "/"
    
    def items(self):
        return Post.live_objects.all().order_by('-created')

class LatestThreadPosts(Feed):
    title = '%s Latest Discussions' % (Site.objects.get_current().name)
    description = "The latest contributions to discussions."
    title_template = "popboard/feeds/latest_title.html"
    description_template = "popboard/feeds/latest_description.html"
    
    def get_object(self, bits):
        if len(bits) != 1:
            raise ObjectDoesNotExist
        return Thread.objects.get(id=int(bits[0]))

    def title(self, obj):
        return "%s Latest Posted on %s" % (Site.objects.get_current(), obj.title,)

    def link(self, obj):
        if not obj:
            raise FeedDoesNotExist
        return obj.get_absolute_url()

    def items(self, obj):
        return Post.live_objects.filter(thread=obj).order_by('created')
       
class LatestCategoryPosts(Feed):
    title = '%s Latest Discussions' % (Site.objects.get_current().name)
    description = "The latest contributions to discussions."
    title_template = "popboard/feeds/latest_title.html"
    description_template = "popboard/feeds/latest_description.html"
    
    def get_object(self, bits):
        if len(bits) != 1:
            raise ObjectDoesNotExist
        return Category.objects.get(id=int(bits[0]))

    def title(self, obj):
        return "%s Latest Posted on %s" % (Site.objects.get_current().name, obj.name,)

    def link(self, obj):
        if not obj:
           raise FeedDoesNotExist
        return obj.get_absolute_url()

    def items(self, obj):
        return Post.live_objects.filter(thread__category=obj).order_by('-created')
       